package cn.edu.swu.auth;

import com.mysql.cj.Session;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class LoginServlet extends HttpServlet {

    private Map<String, User> users = new HashMap<>();

    public void init(ServletConfig config) {
        String userString = config.getInitParameter("users");
        String[] items = userString.split(";");
        for (String item : items) {
            String[] userAndPass = item.split("@");
            User user = new User(userAndPass[0], userAndPass[1]);
            this.users.put(user.getName(), user);
        }
        System.out.println("user data initialized!!");
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("user");
        String pass = request.getParameter("pass");
        String code = request.getParameter("code");

        HttpSession session = request.getSession(true);
        String authcode = (String) session.getAttribute(AuthCodeServlet.AUTH_CODE);
        if (authcode == null || !authcode.equalsIgnoreCase(code)) {
            response.sendRedirect("./admin.html");
            return;
        }

        User user = this.users.get(name);
        if (user != null) {
            if (user.getPass().equals(pass)) {
                response.addCookie(new Cookie("bookstore-user", name));
                session = request.getSession(true);
                session.setAttribute(AuthFilter.LOGIN_TAG, AuthFilter.LOGIN_SUCCESS);

                response.sendRedirect("./book/list");
                return;
            }
        }

        response.sendRedirect("./admin.html");
    }
}
